package users

import (
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	beego "github.com/beego/beego/v2/server/web"
	"strconv"
	"xpms/app/models"
	"xpms/cores/utils"
)

type Positions struct {
	Id     int64 `orm:"pk;column(positionid);" json:"Id,string"`
	Name   string
	Desc   string
	Status int
}

func (this *Positions) TableName() string {
	return models.TableName("positions")
}
func init() {
	orm.RegisterModel(new(Positions))
}

func GetPositions(id int64) (Positions, error) {
	var pos Positions
	var err error
	o := orm.NewOrm()
	pos = Positions{Id: id}
	err = o.Read(&pos)

	if err == orm.ErrNoRows {
		return pos, nil
	}
	return pos, err
}

func GetPositionsByName(name string) (Positions, error) {
	var pos Positions
	var err error
	o := orm.NewOrm()
	err = o.QueryTable(models.TableName("positions")).Filter("name", name).One(&pos)
	if err == orm.ErrNoRows {
		return pos, nil
	}
	return pos, err
}

func GetPositionsName(id int64) string {
	var err error
	var name string
	err = utils.GetCache("GetPositionsName.id."+fmt.Sprintf("%d", id), &name)
	if err != nil {
		cache_expire, _ := beego.AppConfig.Int("cache_expire")
		var pos Positions
		o := orm.NewOrm()
		o.QueryTable(models.TableName("positions")).Filter("positionid", id).One(&pos, "name")
		name = pos.Name
		utils.SetCache("GetPositionsName.id."+fmt.Sprintf("%d", id), name, cache_expire)
	}
	return name
}

func UpdatePositions(id int64, updPos Positions) error {
	var pos Positions
	o := orm.NewOrm()
	pos = Positions{Id: id}

	pos.Name = updPos.Name
	pos.Desc = updPos.Desc
	_, err := o.Update(&pos, "name", "desc")
	return err
}

func AddPositions(updPos Positions) error {
	o := orm.NewOrm()
	pos := new(Positions)

	pos.Id = updPos.Id
	pos.Name = updPos.Name
	pos.Desc = updPos.Desc
	pos.Status = 1
	_, err := o.Insert(pos)

	return err
}

func TestPageExec(condArr map[string]interface{}, page int, offset int) (ops []Positions) {
	o := orm.NewOrm()
	var test []Positions
	o.Raw(PositionPageSql(condArr, 1, page, offset)).QueryRows(&test)
	return test
}

func TestPageCountExec(condArr map[string]interface{}, page int, offset int) int64 {
	o := orm.NewOrm()
	var analysisAllTest int64
	o.Raw(PositionPageSql(condArr, 0, page, offset)).QueryRow(&analysisAllTest)
	return analysisAllTest
}

/**
  组装sql
*/
func PositionPageSql(condArr map[string]interface{}, ifsCount, page int, offset int) (string, []interface{}) {
	var sql string
	if ifsCount == 0 {
		sql = sql + `SELECT count(1) FROM (`
	}
	sql = sql + `
	SELECT
	  pps.*
	FROM pms_positions pps
	WHERE 1 = 1 `
	param := make([]interface{}, 0, 0)
	if !utils.IsEmpty(condArr["keywords"]) {
		sql = sql + ` and  pps.name LIKE concat('%',?,'%')`
		param = append(param, condArr["keywords"])
	}
	if !utils.IsEmpty(condArr["status"]) {
		sql = sql + ` and  pps.status = ?`
		param = append(param, condArr["status"])
	}
	if ifsCount == 0 {
		sql = sql + ` ) C`
	} else if ifsCount > 0 {
		if page < 1 {
			page = 1
		}
		if offset < 1 {
			offset, _ = beego.AppConfig.Int("pageoffset")
		}
		start := (page - 1) * offset
		startStr := strconv.Itoa(start)
		offsetStr := strconv.Itoa(offset)
		sql = sql + ` LIMIT ` + startStr + `,` + offsetStr
	}
	return sql, param
}

func ListPositions(condArr map[string]string) (num int64, err error, pos []Positions) {
	o := orm.NewOrm()
	qs := o.QueryTable(models.TableName("positions"))
	cond := orm.NewCondition()
	if condArr["status"] != "" {
		cond = cond.And("status", condArr["status"])
	}
	qs = qs.SetCond(cond)
	var deps []Positions
	num, err = qs.All(&deps)
	return num, err, deps
}

//更改用户状态
func ChangePositionStatus(id int64, status int) error {
	o := orm.NewOrm()

	pos := Positions{Id: id}
	err := o.Read(&pos, "positionid")
	if nil != err {
		return err
	} else {
		pos.Status = status
		_, err := o.Update(&pos)
		return err
	}
}
